// AuthController.java
package com.tzkyzj.tiremanager.contorller;

import com.tzkyzj.tiremanager.dto.LoginRequest;
import com.tzkyzj.tiremanager.dto.LoginResponse;
import com.tzkyzj.tiremanager.entity.User;
import com.tzkyzj.tiremanager.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private AuthService authService;

    @PostMapping("/login")
    public ResponseEntity<LoginResponse> login(@RequestBody LoginRequest loginRequest,
                                               HttpServletRequest request) {
        System.out.println("登录请求 - 用户名: " + loginRequest.getUsername() + ", 设备类型: " + loginRequest.getDeviceType());

        String ipAddress = getClientIpAddress(request);
        String userAgent = request.getHeader("User-Agent");

        LoginResponse response = authService.login(loginRequest, ipAddress, userAgent);

        if (response.isSuccess()) {
            // 登录成功，将用户信息存入Session
            HttpSession session = request.getSession();
            User user = authService.getUserByUsername(loginRequest.getUsername());
            session.setAttribute("currentUser", user);
            session.setMaxInactiveInterval(30 * 60); // 30分钟超时

            // 更新最后登录时间
            authService.updateLastLoginTime(loginRequest.getUsername());

            System.out.println("登录成功，用户: " + user.getUsername() + ", 角色: " + user.getRole());
        } else {
            System.out.println("登录失败: " + response.getMessage());
        }

        return ResponseEntity.ok(response);
    }

    @PostMapping("/logout")
    public ResponseEntity<Map<String, Object>> logout(HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>();

        // 使Token失效
        String token = request.getHeader("Authorization");
        if (token != null) {
            authService.logout(token);
        }

        // 清除Session
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.invalidate();
        }

        response.put("success", true);
        response.put("message", "退出成功");

        return ResponseEntity.ok(response);
    }

    // 添加一个检查登录状态的接口
    @GetMapping("/check")
    public ResponseEntity<Map<String, Object>> checkAuth(HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>();

        HttpSession session = request.getSession(false);
        if (session != null) {
            User user = (User) session.getAttribute("currentUser");
            if (user != null) {
                response.put("authenticated", true);
                response.put("user", user);
                return ResponseEntity.ok(response);
            }
        }

        response.put("authenticated", false);
        response.put("message", "用户未登录");
        return ResponseEntity.ok(response);
    }

    // 添加权限检查接口
    @GetMapping("/check-permission")
    public ResponseEntity<Map<String, Object>> checkPermission(@RequestParam String resource,
                                                               HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>();

        HttpSession session = request.getSession(false);
        if (session != null) {
            User user = (User) session.getAttribute("currentUser");
            if (user != null) {
                boolean hasPermission = authService.hasPermission(user, resource);
                response.put("hasPermission", hasPermission);
                response.put("user", user);
                return ResponseEntity.ok(response);
            }
        }

        response.put("hasPermission", false);
        response.put("message", "用户未登录");
        return ResponseEntity.ok(response);
    }

    private String getClientIpAddress(HttpServletRequest request) {
        String xForwardedFor = request.getHeader("X-Forwarded-For");
        if (xForwardedFor != null && !xForwardedFor.isEmpty()) {
            return xForwardedFor.split(",")[0];
        }
        return request.getRemoteAddr();
    }



    /**
     * 获取当前用户完整信息
     */
    @GetMapping("/user-info")
    public ResponseEntity<Map<String, Object>> getCurrentUserInfo(HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>();

        HttpSession session = request.getSession(false);
        if (session == null) {
            response.put("authenticated", false);
            response.put("message", "用户未登录");
            return ResponseEntity.ok(response);
        }

        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            response.put("authenticated", false);
            response.put("message", "用户信息不存在");
            return ResponseEntity.ok(response);
        }

        // 返回完整的用户信息
        response.put("authenticated", true);
        response.put("user", Map.of(
                "id", currentUser.getId(),
                "username", currentUser.getUsername(),
                "role", currentUser.getRole(),
                "transportCompany", currentUser.getTransportCompany(),
                "vehiclePlateNumber", currentUser.getVehiclePlateNumber(),
                "enabled", currentUser.getEnabled()
        ));

        return ResponseEntity.ok(response);
    }
}